//
//  WBUserAccount.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/7.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

fileprivate let userAccountKey = "userAccountKey"

class WBUserAccount: NSObject {
    /// 单例
    static let shared: WBUserAccount  = WBUserAccount()
    
    /// token
    var access_token: String?
    
    /// 过期秒数
    var expires_in: Double = 0 {
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// token的过期时间
    var expires_date: Date?
    
    /// 用户id
    var uid: String?
    
    /// 用户的昵称
    var screen_name: String?
    
    /// 用户头像
    var avatar_large: String?
    
    /// 用户是否登录（计算属性）
    var isLogin: Bool {
        return access_token != nil && Date().compare(expires_date!) == .orderedAscending
    }

    override init() {
        super.init()
        read()
    }
    
    /// 从沙盒中获取用户有信息
    func read() {
        if let userInfo = UserDefaults.standard.value(forKey: userAccountKey) as? [String: Any] {
            //使用kvc的方式，对所有的属性赋值
            setValuesForKeys(userInfo)
        }
    }
    
    /// 将从服务器获取的用户信息保存到沙盒
    func save(dict: [String: Any]) {
        //使用kvc的方式，对所有的属性赋值
        setValuesForKeys(dict)
        //将模型转字典, keys这模型的属性的名的数组
        let modelDic = dictionaryWithValues(forKeys: ["access_token", "expires_date", "uid", "screen_name", "avatar_large"])
        
        //将字典保存到沙盒
        UserDefaults.standard.set(modelDic, forKey: userAccountKey)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
